package com.tre.jdevtemplateboot.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tre.jdevtemplateboot.common.util.json.JsonObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * @program: jdev-boot-core
 * @description
 * @author: JDev
 * @create: 2021-07-30 08:27
 **/
public class JsonUtils {

    private static final ObjectMapper MAPPER = new JsonObjectMapper();

    private JsonUtils() {
    }

    public static String objectToJson(Object data) throws JsonProcessingException {
        return MAPPER.writeValueAsString(data);
    }

    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) throws IOException {
        return MAPPER.readValue(jsonData, beanType);
    }

    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) throws IOException {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        return MAPPER.readValue(jsonData, javaType);
    }
}
